package org.jash.ting13.home

import androidx.lifecycle.viewModelScope
import androidx.paging.Pager
import androidx.paging.PagingConfig
import androidx.paging.cachedIn
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.flow.take
import kotlinx.coroutines.launch
import org.jash.ting13.net.APIService
import org.jash.utils.log
import org.jash.utils.mvi.BaseViewModel
import org.jash.utils.net.service
import java.nio.charset.StandardCharsets

class HomeViewModel:BaseViewModel<HomeIntent, HomeState>() {
    private val service: APIService by lazy { service() }
    init {
        viewModelScope.launch {
            intent.consumeAsFlow().collect {
                when (it) {
                    is HomeIntent.LoadHome -> loadHome()
                    is HomeIntent.LoadPaging -> loadPaging(it.keyword)
                }
            }
        }
    }
    private suspend fun loadHome() {
        val s = try {
            HomeState.Success(service.getHome())
        } catch (e:Exception) {
            HomeState.Failure(e.message ?: "")
        }
        state.postValue(s)
    }
    private suspend fun loadPaging(keyword:String) {
        log("loadPaging: $keyword")
//        val kw = keyword.toByteArray(StandardCharsets.UTF_8).joinToString("") { String.format("oOo%02x", it) }
        Pager(PagingConfig(10)) {
            SearchPagingSource(service, keyword)
        }.flow.cachedIn(viewModelScope).take(1).collect {
            state.postValue(HomeState.Paging(it))
        }

    }
}